package com.hmdp.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisUtils redisUtils;
    @Override
    public Result queryById(Long id) {
        Shop shop = redisUtils.cacheRebuild(id, RedisConstants.CACHE_SHOP_KEY,
                RedisConstants.LOCK_SHOP_KEY, RedisConstants.CACHE_SHOP_TTL
                ,TimeUnit.SECONDS,Shop.class, this::getById);
        return Result.ok(shop);
    }

    @Override
    public void updateShop(Shop shop) {
        if(shop.getId()==null){
            return;
        }
        updateById(shop);
        stringRedisTemplate.delete("cache:shop:" + shop.getId());
    }

    @Override
    public void saveWithExpired(Shop shop) {
        save(shop);
        String key = RedisConstants.CACHE_SHOP_KEY + shop.getId();
        RedisData<Shop> redisData = new RedisData(LocalDateTime.now().plusSeconds(RedisConstants.CACHE_SHOP_TTL),shop);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
}